<?php

namespace App\Http\Controllers\Api;

use App\Models\Area;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class AreaController extends BaseController
{
    public function index(Request $request)
    {
        $area = \Storage::disk('public')->get('area.json');
        $items = json_decode($area,true);
        $data = [
            'items' => $items
        ];
        return $this->res([
            'data' => $data
        ]);
    }

    /*
     * 保存到文件
     */
    public function storeFile()
    {
        set_time_limit(0);
        $list = Area::all()->toArray();
        //$items = $this->getTree($list, 0 , 1);
        $items = self::list2tree($list);

        \Storage::disk('public')->put('area.json', json_encode($items));
    }

    public static function list2tree($list, $pk='id', $pid = 'pid', $child = '_child', $root = 0)
    {
        // 创建Tree
        $tree = array();
        if(is_array($list)) {
            // 创建基于主键的数组引用
            $refer = array();
            foreach ($list as $key => $data) {
                $refer[$data[$pk]] =& $list[$key];
            }
            foreach ($list as $key => $data) {
                // 判断是否存在parent
                $parentId =  $data[$pid];
                if ($root == $parentId) {
                    $tree[] =& $list[$key];
                }else{
                    if (isset($refer[$parentId])) {
                        $parent =& $refer[$parentId];
                        $parent[$child][] =& $list[$key];
                    }
                }
            }
        }
        return $tree;
    }
}
